<template>
  <div class="">
    <el-form ref="goodsInventoryAddForm" :model="goodsInventoryAddForm" :rules="goodsInventoryAddFormRule"
             label-width="80px" >
<!--      <div class="mx">
        <el-button class="button"  type="primary" v-if="type !== 'detail'"
                   @click="handleSelectWarehouseEntryBatch">添加物料</el-button>
      </div>-->
      <el-row v-if="optType != 'view'" :gutter="10">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleSelectWarehouseEntryBatch"
          >新增
          </el-button>
        </el-col>
      </el-row>

      <!--      <div class="prolist" >-->
      <el-form-item style="width: 100%;" class="aa" prop="productList">

        <el-input v-if="false" v-model="goodsInventoryAddForm.suId"/>

        <el-table :data="goodsInventoryAddForm.productList" border :cell-style="{ textAlign: 'center' }"
                  :header-cell-style="{ textAlign: 'center' }" style="width: 100%; margin-top: 20px;">
          <el-table-column label="序号"
                           type="index"
                           width="50">
          </el-table-column>
          <el-table-column v-if="false" label="suId" align="center" prop="suId">
            <template slot-scope="scope">
              <el-input v-model="scope.row.suId" readonly></el-input>
            </template>
          </el-table-column>
          <el-table-column label="商品编号" align="center" prop="itemCode">
            <template slot-scope="scope">
              {{ scope.row.itemCode }}
            </template>
          </el-table-column>
          <el-table-column label="商品名称" align="center" prop="itemName">
            <template slot-scope="scope">
              {{ scope.row.itemName }}
            </template>
          </el-table-column>
          <el-table-column label="规格型号" align="center" prop="specification">
            <template slot-scope="scope">
              {{ scope.row.specification }}
            </template>
          </el-table-column>
          <el-table-column label="单位（主）" align="center" prop="unitOfMeasure">
            <template slot-scope="scope">
              {{ scope.row.unitOfMeasure }}
            </template>
          </el-table-column>
          <el-table-column label="批次号" align="center" prop="batchCode">
            <template slot-scope="scope">
              {{ scope.row.batchCode }}
            </template>
          </el-table-column>
          <el-table-column label="品牌" align="center" prop="itemBrand">
            <template slot-scope="scope">
              {{ scope.row.unitOfMeasure }}
            </template>
          </el-table-column>
          <el-table-column label="颜色" align="center" prop="itemColor">
            <template slot-scope="scope">
              {{ scope.row.itemColor }}
            </template>
          </el-table-column>
          <el-table-column label="技术要求" align="center" prop="itemTechReq">
            <template slot-scope="scope">
              {{ scope.row.itemTechReq }}
            </template>
          </el-table-column>
          <el-table-column label="型号" align="center" prop="itemModel">
            <template slot-scope="scope">
              {{ scope.row.itemModel }}
            </template>
          </el-table-column>
          <el-table-column label="仓库" align="center" prop="unitOfMeasure">
            <template slot-scope="scope">
              {{ scope.row.warehouseName }}
            </template>
          </el-table-column>
          <el-table-column label="库区" align="center" prop="unitOfMeasure">
            <template slot-scope="scope">
              {{ scope.row.locationName }}
            </template>
          </el-table-column>
          <el-table-column label="库位" align="center" prop="unitOfMeasure" width="90">
            <template slot-scope="scope">
              {{ scope.row.areaName }}
            </template>
          </el-table-column>
          <el-table-column label="库存数量（主）" align="center" prop="quantityOnhand">
            <template slot-scope="scope">
              {{scope.row.quantityOnhand}}
            </template>
          </el-table-column>
          <el-table-column label="盘点数量（主）" align="left" prop="inventoryNum">
            <template slot-scope="scope">
              <el-input  type="number" :min="0" :maxlength="90000000000" size="mini" style="width:100px"  @change="handleEdit(scope.$index, scope.row)"
                         v-model="scope.row.inventoryNum"  :disabled="optType === 'view' || type === 'audit'"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="差异（主）" align="center" prop="diffNum">
            <template slot-scope="scope">
              <!--                {{ scope.row.inventory_num - scope.row.remain_num || 0 }}-->
              <el-input  v-model="scope.row.diffNum" placeholder="差异" size="mini" style="width:100px" readonly="readonly" :disabled="optType === 'view'"></el-input>
            </template>
          </el-table-column>
          <!--            <el-table-column label="分类名称" align="center" prop="itemTypeName">
                        <template slot-scope="scope">
                          {{ scope.row.itemTypeName }}
                        </template>
                      </el-table-column>-->
          <el-table-column label="单位（辅）" align="center" prop="storageUnit"  />
          <el-table-column label="库存数量（辅）" align="center" prop="storageUnitquantity"/>
          <el-table-column label="盘点数量（辅）" align="left" prop="storageInventoryNum">
            <template slot-scope="scope">
              <el-input  type="number" :min="0" :maxlength="90000000000" size="mini" style="width:100px"
                         v-model="scope.row.storageInventoryNum"  :disabled="optType === 'view' || type === 'audit'"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="差异（辅）" align="center" prop="storageDiffNum">
            <template slot-scope="scope">
              <!--                {{ scope.row.inventory_num - scope.row.remain_num || 0 }}-->
              <el-input  v-model="scope.row.storageDiffNum" placeholder="差异" size="mini" style="width:100px" readonly="readonly" :disabled="optType === 'view'"></el-input>
            </template>
          </el-table-column>

          <el-table-column label="备注" align="center" prop="remark">
            <template slot-scope="scope">
              <el-input v-model="scope.row.remark"></el-input>

            </template>
          </el-table-column>
          <el-table-column
            v-for="col in columnsConfig"
            :key="col.prop"
            :label="col.label"
            :prop="col.prop"
            :width="col.width"
            :align="col.align"
            v-if="col.show">
          </el-table-column>

          <!--            @click="goodsInventoryAddForm.productList.splice(scope.$index, 1)" v-if="optType != 'view'"-->
          <el-table-column label="操作"   v-if="false">
            <template slot-scope="scope">
              <el-button size="mini" type="danger"
                         @click="deleteProduct(scope.$index,scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-form-item>
      <!--      </div>-->
    </el-form>

<!--    <div slot="footer" class="dialog-footer" style="text-align:center;margin-top: 20px;">
      <el-button type="primary" @click="submitGoodsInventoryAddForm">保存</el-button>
      <el-button type="primary" @click="cancel">返 回</el-button>
    </div>-->

<!--    <UserSingleSelect ref="userSelect" @onSelected="onUserSelected"></UserSingleSelect>-->
    <ItemSelect ref="itemSelect" @onSelected="onItemSelected" :warehouse-info="warehouseInfo" v-if="warehouseInfo && zujFlag" > </ItemSelect>

  </div>
</template>

<script>

import $ from 'jquery';
import {getTreeList} from "@/api/mes/wm/warehouse";
import ItemSelect  from "@/components/itemSelect/multi.vue";
import { listSurplusProduct, getSurplusProduct, delSurplusProduct, addSurplusProduct, updateSurplusProduct } from "@/api/mes/wm/surplusProduct";
import UserSingleSelect from "@/components/userSelect/single.vue"
import {genCode} from "@/api/system/autocode/rule";
import {getProductByPId,deleteProByPidItemId} from "@/api/mes/wm/pandianproduct";
import {addProducts } from "@/api/mes/wm/surplus";
import Template from "@/views/print/printtemplate/list.vue";
import {getColumnsConfigKey} from "@/api/system/columnsconfig";
export default {
  name: 'goodsInventoryAdd',
  components: {Template, UserSingleSelect, ItemSelect},
  props:{
    suId:null,
    optType:null,
    warehouseInfo: {
      type: Array,
      default:[]
    }
  },
  data() {
    return {
      columnsConfig:[],
      total: 0,
      visible:false,
      disabled:true,
      //自动生成编码
      autoGenFlag:false,
      // warehouseInfo:[],
      zujFlag:false,
      warehouseOptions:[],
      warehouseProps:{
        multiple: false,
        value: 'pId',
        label: 'pName',
      },
      adminList: [],
      dialogVisible: false,
      warehouseList: [],
      deptList: [],
      deptListAll: [],
      id: '',
      type: '',
      /** 出库单表单*/
      goodsInventoryAddForm: {
        suId: this.suId,
        productList: []
      },
      /** 校验规则 */
      goodsInventoryAddFormRule: {
        // inventory_person_id: { required: true, message: '请选择盘点人', trigger: 'change' },
        warehouseInfo: { required: true, message: '请选择报仓库', trigger: 'change' },

      },
      warehouseProduct: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        suId: this.suId,
        itemId: null,
        itemCode: null,
        itemName: null,
        specification: null,
        unitOfMeasure: null,
        quantityRt: null,
        batchCode: null,
        warehouseId: null,
        warehouseCode: null,
        warehouseName: null,
        locationId: null,
        locationCode: null,
        locationName: null,
        areaId: null,
        areaCode: null,
        areaName: null
      },
    };
  },
  created() {
    this.goodsInventoryAddForm.suId=this.suId
    this.getWarehouseList()
    this.getList()
    this.getItemBase()
  },
  methods: {
    /** 查询修改 */
    getList() {
      console.log("line",this.warehouseInfo)
      //查询详情
      listSurplusProduct(this.queryParams).then(response => {
        this.goodsInventoryAddForm.productList=response.rows
        this.total = response.total;
        this.zujFlag=true
      });
      this.$forceUpdate()
    },
    getItemBase(){
      getColumnsConfigKey('MdItem_Base').then(res=>{
        this.columnsConfig = JSON.parse(res.data);
      })
    },
    //编辑修改物料 删除
    deleteProduct(index,row){
      if(this.goodsInventoryAddForm.id){

        this.$confirm('确定要删除物料 “'+row.itemCode + row.itemName +'" 的数据？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteProByPidItemId(this.goodsInventoryAddForm.id,row.itemId)
          this.goodsInventoryAddForm.productList.splice(index, 1)
          row.diffNum=0
          row.inventoryNum=0
          row.remark=''
          console.log("del hou",this.goodsInventoryAddForm.productList)
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          // this.$router.go(0)
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });


      }else{
        this.$message.warning("无法删除，请联系管理员")
      }

    },

    //自动生成编码
    handleAutoGenChange(autoGenFlag){
      if(autoGenFlag){
        genCode('PANDIAN_CODE').then(response =>{
          this.goodsInventoryAddForm.sn = response;
          this.$forceUpdate()
        });
      }else{
        this.goodsInventoryAddForm.sn = null;
        this.$forceUpdate()
      }
      this.$forceUpdate()
    },
    //点击人员选择按钮
    handleUserSelect(){
      this.$refs.userSelect.showFlag = true;
    },
    //人员选择返回
    onUserSelected(row){
      this.goodsInventoryAddForm.inventoryPerson= row.userName;
      this.goodsInventoryAddForm.inventoryPersonId= row.userId;
      this.$forceUpdate()
    },
    /** 提交按钮 */
    submitGoodsInventoryAddForm() {
/*      this.goodsInventoryAddForm.productList.some(item => {
        item.suId = this.suId
      })*/
      console.log("wwwww",this.goodsInventoryAddForm.productList)
      this.$refs["goodsInventoryAddForm"].validate(valid => {
        if (valid) {
          if (this.goodsInventoryAddForm.suId != null) {
            addProducts(this.goodsInventoryAddForm).then(response => {
              this.$modal.msgSuccess("修改成功");

            /*  this.visible = false;
              this.$emit('refreshDataList')*/
              /*   //刷新列表
                 localStorage.setItem("IndexRefresh", true);
                 this.$store.dispatch("tagsView/delView", this.$route)
                 // this.$router.push({path: '/pandian/pandian'});
                 this.$router.go(-1)*/
            });
          }
        }
      });


    },
    // 取消按钮
    cancel() {
      /* localStorage.setItem("IndexRefresh", true);
       // 调用全局挂载的方法，关闭当前页
       this.$store.dispatch("tagsView/delView", this.$route)
       this.$router.go(-1)*/
      // 取消按钮
      this.visible = false;
      this.$emit('refreshDataList')
    },
    //商品差
    handleEdit(index, row) {
      if( row.inventoryNum){
        // row.diffNum = parseFloat(Number(row.inventoryNum)-Number(row.quantityOnhand)).toFixed(2)
        row.diffNum = Number(row.inventoryNum) - Number(row.quantityOnhand)
        console.log(row.diffNum)
      }
    },
    // 选择出库单
    handleSelectWarehouseEntryBatch() {

      console.log("handleSelectWarehouseEntryBatch",this.warehouseInfo)
      if (!this.warehouseInfo) {
        this.$message.error('请先选择仓库！')
        return
      }
      this.$refs.itemSelect.showFlag = true;

    },
    //物料选择弹出框
    onItemSelected(obj){
      console.log("obj",obj)
      if(this.goodsInventoryAddForm.productList.length >0){
        // 看所选物料是否重复
        var commonElements = $.grep(this.goodsInventoryAddForm.productList, function(element) {
          return $.grep(obj, function(el) {
            if(el.itemId === element.itemId && el.batchCode == element.batchCode){
              return el.itemId === element.itemId;
            }
          }).length > 0;
        })

        if(commonElements.length > 0){
          this.$message.warning("物料存在重复请重新选择")
          return
        }
        this.goodsInventoryAddForm.productList=this.goodsInventoryAddForm.productList.concat(obj)

      }else{
        //第一次增加
        obj.some(item => { item.suId = this.suId})
        this.goodsInventoryAddForm.productList=obj
      }
      console.log("onItemSelected plist",this.goodsInventoryAddForm.productList)
    },
    //选择默认的仓库、库区、库位
    handleWarehouseChanged(obj){
      console.log("handleWarehouseChanged",obj)
      const selectedNodes = this.$refs.selectck.getCheckedNodes();
      console.log("selectedNodes",selectedNodes)
      console.log('选中的名称11:',selectedNodes[0].pathLabels)
      if(obj !=null){
        this.goodsInventoryAddForm.warehouseId = obj[0];
        this.goodsInventoryAddForm.locationId = obj[1];
        this.goodsInventoryAddForm.areaId = obj[2];
        this.goodsInventoryAddForm.warehouseName=selectedNodes[0].pathLabels[0]
        this.goodsInventoryAddForm.locationName=selectedNodes[0].pathLabels[1]
        this.goodsInventoryAddForm.areaName=selectedNodes[0].pathLabels[2]
      }
    },
    getWarehouseList(){
      getTreeList().then( response =>{
        if(response.data){
          this.warehouseOptions = response.data.filter((el) =>{
            return el.warehouseCode.indexOf('VIR') == -1;
          });;
        }
        // console.log("1111",this.warehouseOptions)
        this.warehouseOptions.map(w =>{
          w.children.map(l =>{
            let lstr =JSON.stringify(l.children).replace(/locationId/g,'lId').replace(/areaId/g, 'pId').replace(/areaName/g,'pName');
            l.children = JSON.parse(lstr);
          });

          let wstr = JSON.stringify(w.children).replace(/warehouseId/g,'wId').replace(/locationId/g, 'pId').replace(/locationName/g,'pName');
          w.children =  JSON.parse(wstr);

        });
        let ostr=JSON.stringify(this.warehouseOptions).replace(/warehouseId/g,'pId').replace(/warehouseName/g, 'pName');
        this.warehouseOptions = JSON.parse(ostr);
        // console.log('2222',JSON.parse(ostr))
      });
    },
  }


}
</script>
<style type="text/css" scoped>
.mx{
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  align-content: center;
  justify-content: flex-start;
  align-items: center;
  .button {
    margin-left: 10px;
  }
}
.aa >>> .el-form-item__content {
  margin-left:0px !important;
}
</style>

<!--
<style type="text/css" scoped>
.mx{
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  align-content: center;
  justify-content: flex-start;
  align-items: center;
  .button {
    margin-left: 10px;
  }
}

/** 底部步骤 */
.footer {
  width: 100%;
  padding: 10px;
  bottom: 0px;
  text-align: center;
  z-index: 999;
}

.mx {
  display: flex;
  align-items: center;
  width: 100%;

  .button {
    margin-left: 10px;
  }

}
.prolist {
  width: 100%;
  display: flex;
  /deep/ {
    .el-form&#45;&#45;inline .el-form-item__content {
      display: flex;
    }
  }
}

/*.change-form {
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
  flex-wrap: wrap;
  min-width: 900px;

  .change-form-item {
    width: 100%;
    margin: 0 10px 20px 0;
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
  }

  /deep/ {
    .el-form-item__content {
      flex: 1;
      width: 100%;
    }

    .el-date-editor,
    .el-cascader,
    .el-select {
      width: 100%;
    }
  }
}*/

.bg-in-stock {
  background-color: #fff;
  margin: 10px;
  padding: 25px;
}

.goods-info {
  display: flex;

  .goods-name-box {
    text-align: left;

    .goods-name {
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
      line-height: 16px;
    }

    .specs {
      color: #999999;
    }
  }
}

/deep/ {
  .el-input&#45;&#45;suffix .el-input__inner {
    padding-right: 10px;
  }

  .error-input {
    .el-input__inner {
      border: 1px solid red;
    }
  }
}
</style>
-->
